<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库区编号" prop="whAreaNo">
        <el-input v-model="queryParams.whAreaNo" placeholder="请输入库区编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="库区名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入库区名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="专业类别" prop="fieldSortCode">
        <el-select v-model="queryParams.fieldSortCode" placeholder="请选择专业类别" clearable>
          <el-option v-for="dict in dict.type.ra_field_sort_code" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['storage:mdWhAreaInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['storage:mdWhAreaInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['storage:mdWhAreaInfo:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-sort" size="mini" @click="downloadData" v-hasPermi="['storage:mdWhAreaInfo:downloadJsonMdWhAreaInfo']">下载数据</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['storage:mdWhAreaInfo:importDataMdWhAreaInfo']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['storage:mdWhAreaInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mdWhAreaInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库区标识" align="center" prop="whAreaId" min-width="120px" />
      <el-table-column label="操作标识" align="center" prop="operId" v-if="false" />
      <el-table-column label="库房标识" align="center" prop="whId" v-if="false" />
      <el-table-column label="库区编号" align="center" prop="whAreaNo" />
      <el-table-column label="库区名称" align="center" prop="name" min-width="100px" />
      <el-table-column label="库房名称" align="center" prop="whName" min-width="200px" />
      <el-table-column label="库区类别" align="center" prop="typeCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ra_type_code" :value="scope.row.typeCode" />
        </template>
      </el-table-column>
      <el-table-column label="功能类别" align="center" prop="funcTypeCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ra_func_type_code" :value="scope.row.funcTypeCode" />
        </template>
      </el-table-column>
      <el-table-column label="专业类别" align="center" prop="fieldSortCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ra_field_sort_code" :value="scope.row.fieldSortCode" />
        </template>
      </el-table-column>
      <el-table-column label="库区状态" align="center" prop="statusCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ra_status_code" :value="scope.row.statusCode" />
        </template>
      </el-table-column>
      <el-table-column label="库区面积" align="center" prop="whAreaSize" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="170px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['storage:mdWhAreaInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['storage:mdWhAreaInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改库区信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="title == '添加库区信息'">
        <el-form-item label="库区标识" prop="whAreaId">
          <el-input v-model="form.whAreaId" placeholder="请输入库区标识" maxlength="16" />
        </el-form-item>
        <el-form-item label="操作标识" prop="operId" v-if="false">
          <el-input v-model.number="form.operId" placeholder="请输入操作标识" />
        </el-form-item>
        <el-form-item label="库房" prop="whId">
          <el-select v-model="form.whId" placeholder="请选择库房">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区编号" prop="whAreaNo">
          <el-input v-model="form.whAreaNo" placeholder="请输入库区编号" maxlength="256" />
        </el-form-item>
        <el-form-item label="库区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入库区名称" maxlength="256" />
        </el-form-item>
        <el-form-item label="库区类别" prop="typeCode">
          <el-select v-model="form.typeCode" placeholder="请选择库区类别" clearable>
            <el-option v-for="dict in dict.type.ra_type_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区状态" prop="statusCode">
          <el-select v-model="form.statusCode" placeholder="请选择库区状态" clearable>
            <el-option v-for="dict in dict.type.ra_status_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="功能类别" prop="funcTypeCode">
          <el-select v-model="form.funcTypeCode" placeholder="请选择功能类别" clearable>
            <el-option v-for="dict in dict.type.ra_func_type_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业类别" prop="fieldSortCode">
          <el-select v-model="form.fieldSortCode" placeholder="请选择专业类别" clearable>
            <el-option v-for="dict in dict.type.ra_field_sort_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区面积" prop="whAreaSize">
          <el-input v-model="form.whAreaSize" placeholder="请输入库区面积" />
        </el-form-item>
      </el-form>
      <el-form ref="forms" :model="forms" :rules="rules" label-width="80px" v-if="title == '修改库区信息'">
        <el-form-item label="库区标识" prop="whAreaId">
          <el-input v-model="forms.whAreaId" placeholder="请输入库区标识" disabled />
        </el-form-item>
        <el-form-item label="操作标识" prop="operId" v-if="false">
          <el-input v-model.number="forms.operId" placeholder="请输入操作标识" />
        </el-form-item>
        <el-form-item label="库房" prop="whId">
          <el-select v-model="forms.whId" placeholder="请选择库房">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区编号" prop="whAreaNo">
          <el-input v-model="forms.whAreaNo" placeholder="请输入库区编号" maxlength="256" />
        </el-form-item>
        <el-form-item label="库区名称" prop="name">
          <el-input v-model="forms.name" placeholder="请输入库区名称" maxlength="256" />
        </el-form-item>
        <el-form-item label="库区类别" prop="typeCode">
          <el-select v-model="forms.typeCode" placeholder="请选择库区类别" clearable>
            <el-option v-for="dict in dict.type.ra_type_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区状态" prop="statusCode">
          <el-select v-model="forms.statusCode" placeholder="请选择库区状态" clearable>
            <el-option v-for="dict in dict.type.ra_status_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="功能类别" prop="funcTypeCode">
          <el-select v-model="forms.funcTypeCode" placeholder="请选择功能类别" clearable>
            <el-option v-for="dict in dict.type.ra_func_type_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业类别" prop="fieldSortCode">
          <el-select v-model="forms.fieldSortCode" placeholder="请选择专业类别" clearable>
            <el-option v-for="dict in dict.type.ra_field_sort_code" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区面积" prop="whAreaSize">
          <el-input v-model="forms.whAreaSize" placeholder="请输入库区面积" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的库区数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate" v-hasPermi="['storage:mdWhAreaInfo:importTemplateMdWhAreaInfo']">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMdWhAreaInfo, getMdWhAreaInfo, delMdWhAreaInfo, addMdWhAreaInfo, updateMdWhAreaInfo } from "@/api/meter/mdWhAreaInfo";
import { selectMdWhInfo } from '@/api/meter/mdWhInfo';
import { jsonMdWhAreaInfo } from "@/api/meter/downloadData";
import { getToken } from "@/utils/auth";

export default {
  name: "MdWhAreaInfo",
  dicts: ['ra_type_code', 'ra_func_type_code', 'ra_field_sort_code', 'ra_status_code'],
  data() {
    //自定义验证表单数聚长度
    let operIdValidate = (rule, value, callback) => {
      if (value) {
        if (value.length > 16) {
          callback(new Error("输入长度不得长于16个字符"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    let numberValidate = (rule, value, callback) => {
      if (value) {
        if (value.length > 32) {
          callback(new Error("输入长度不得长于32个字符"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库区信息表格数据
      mdWhAreaInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        operId: null,
        whId: null,
        whAreaNo: null,
        name: null,
        typeCode: null,
        funcTypeCode: null,
        fieldSortCode: null,
        statusCode: null,
        whAreaSize: null
      },
       // 导入参数
       upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/meter/mdWhAreaInfo/importDataMdWhAreaInfo"
      },
      // 表单参数
      form: {},
      forms: {},
      // 表单校验
      rules: {
        //库区标识
        whAreaId: [{
          required: true,
          message: '库区标识不能为空',
          trigger: 'blur'
        },
        {
          pattern: /^[1-9]\d{0,15}$/,
          message: '库区标识不能为0，长度不得超过16位数字'
        },
        ],
        //库房编号
        whAreaNo: [{
          required: true,
          message: '库房编号不能为空',
          trigger: 'blur'
        }, {
          // min: 3,
          max: 256,
          message: '长度不得超过256个字符',
          trigger: 'blur'
        }],
        //库房名称
        name: [{
          required: true,
          message: '库房名称不能为空',
          trigger: 'blur'
        }, {
          // min: 3,
          max: 256,
          message: '长度不得超过256个字符',
          trigger: 'blur'
        }],
        //库房标识
        whId: [{
          required: true,
          message: '库房标识不能为空',
          trigger: 'change'
        }],
        //操作标识
        operId: [{
          required: false,
          validator: operIdValidate,
          trigger: 'blur'
        }],
        //库区面积
        whAreaSize: [{
          required: false,
          validator: numberValidate,
          trigger: 'blur'
        }],
        //库区状态
        statusCode: [{
          required: true,
          message: '请选择库区状态',
          trigger: 'change'
        }],
        //库区类别
        typeCode: [{
          required: true,
          message: '请选择库区类别',
          trigger: 'change'
        }]
      },
      //下拉框信息
      options: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询库区信息列表 */
    getList() {
      this.loading = true;
      listMdWhAreaInfo(this.queryParams).then(response => {
        this.mdWhAreaInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        whAreaId: null,
        operId: null,
        whId: null,
        whAreaNo: null,
        name: null,
        typeCode: null,
        funcTypeCode: null,
        fieldSortCode: null,
        statusCode: null,
        whAreaSize: null
      };
      this.forms = {
        operId: null,
        whId: null,
        whAreaNo: null,
        name: null,
        typeCode: null,
        funcTypeCode: null,
        fieldSortCode: null,
        statusCode: null,
        whAreaSize: null
      }
      this.resetForm("form");
      this.resetForm("forms")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.whAreaId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      selectMdWhInfo().then(response => {
        this.options = response.data
        this.form.whId = this.options[0].value
        this.form.statusCode = "01"
        this.form.typeCode = "01"
        this.open = true;
        this.title = "添加库区信息";
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const whAreaId = row.whAreaId || this.ids
      getMdWhAreaInfo(whAreaId).then(response => {
        this.forms = response.data;
        selectMdWhInfo().then(response => {
          this.options = response.data
          this.open = true;
          this.title = "修改库区信息";
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      let mdWhAreaInfoList = JSON.parse(JSON.stringify(this.mdWhAreaInfoList))
      //判断新增或是修改操作
      if (this.title == "修改库区信息") {
        this.$refs["forms"].validate(valid => {
          if (valid) {
            updateMdWhAreaInfo(this.forms).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        })
      } else if (this.title == "添加库区信息") {
        //新增时，查询已有数据，使主键ID不重复
        let item = mdWhAreaInfoList.find((value) => {
          return value.whAreaId == this.form.whAreaId
        })
        if (item == undefined) {
          this.$refs["form"].validate(valid => {
            if (valid) {
              addMdWhAreaInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          })
        } else {
          this.$message.error('您输入的库区标识重复，请重新输入');
        }

      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const whAreaIds = row.whAreaId || this.ids;
      this.$modal.confirm('是否确认删除库区信息编号为"' + whAreaIds + '"的数据项？').then(function () {
        return delMdWhAreaInfo(whAreaIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('meter/mdWhAreaInfo/export', {
        ...this.queryParams
      }, `mdWhAreaInfo_.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('meter/mdWhAreaInfo/importTemplateMdWhAreaInfo', {
      }, `库区导入模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //下载数据按钮
    downloadData() {
      if (this.ids.length == 0) {
        let array = [];
        let queryParams = {
          whAreaIds: array
        }
        this.$confirm('此操作将下载所有文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          jsonMdWhAreaInfo(queryParams).then(response => {
            if (response.code == 200) {
              this.$message({
                message: `数据成功下载至${response.msg}中`,
                type: 'success'
              });
            } else {
              this.$message.error('数据下载失败');
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消下载'
          });
        });
      } else {
        let queryParams = {
          whAreaIds: JSON.parse(JSON.stringify(this.ids))
        }
        jsonMdWhAreaInfo(queryParams).then(response => {
          if (response.code == 200) {
            this.$message({
              message: `数据成功下载至${response.msg}中`,
              type: 'success'
            });
          } else {
            this.$message.error('数据下载失败');
          }
        })
      }
    }
  }
};
</script>
